<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/5/18
 * Time: 9:32
 */

namespace app\service\order;

use app\company\model\StoreUser;
use app\mini\model\StoreUserAccountDetail;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;
use WePayV3\Order;

class Refund extends Base
{

    /**
     * 退款
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws InvalidResponseException
     * @throws LocalCacheException
     * @throws Exception
     */
    public function update(): void
    {
        //计算退款金额
        $money = $this->order->storeOrderDetails()->sum('amount');
        //微信支付 ....
        if ($this->order->pay_type == 2) {
            $out_refund_no = strval(time());
            $result        = Order::instance(getWxConfig(['company_id' => $this->order->company_id]))->createRefund([
                'out_trade_no'  => $this->order->no,
                'out_refund_no' => $out_refund_no,
                'amount'        => ['refund' => $money * 100, 'total' => $money * 100, 'currency' => 'CNY']
            ]);
            Log::info('退款结果--'.json_encode($result));
            if (!in_array($result['status'],['PROCESSING',"SUCCESS"])) {
                exception('退款失败');
            }
        }

        //余额支付
        if ($this->order->pay_type == 4) {
            if ($salesman_id = $this->order->salesman_id) {
                $user = StoreUser::where('id', $salesman_id)->find();//业务员
            } else {
                $user = $this->order->storeUser()->find();

            }
            $amount = $user->storeUserAccountO()->find();
            $amount->inc('money', $money)->update();
            StoreUserAccountDetail::add($user->id, $amount->id, $money, 7);//添加日志记录
        }

        //大额支付 目前不需要做任务处理
        if ($this->order->pay_type == 5) {

        }

        //账期支付
        if ($this->order->pay_type == 3) {
            $this->order->storeUserCreditO->delete();//找到账单删除
        }
    }
}